package com.gscitysfy.cus.drain.modules.command.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cus.drain.constants.DicConstant;
import com.gscitysfy.cus.drain.constants.RedisKeyConstant;
import com.gscitysfy.cus.drain.modules.command.convert.SchemeManageConvert;
import com.gscitysfy.cus.drain.modules.command.dto.SchemeManageAuditDto;
import com.gscitysfy.cus.drain.modules.command.dto.SchemeManageDto;
import com.gscitysfy.cus.drain.modules.command.dto.SchemeManageExcelDto;
import com.gscitysfy.cus.drain.modules.command.entity.DrainCommandDispatchSchemeCar;
import com.gscitysfy.cus.drain.modules.command.entity.DrainCommandDispatchSchemeTeam;
import com.gscitysfy.cus.drain.modules.command.entity.ReservePlanManage;
import com.gscitysfy.cus.drain.modules.command.entity.SchemeManage;
import com.gscitysfy.cus.drain.modules.command.mapper.DrainCommandDispatchSchemeCarMapper;
import com.gscitysfy.cus.drain.modules.command.mapper.DrainCommandDispatchSchemeTeamMapper;
import com.gscitysfy.cus.drain.modules.command.mapper.SchemeManageMapper;
import com.gscitysfy.cus.drain.modules.command.service.IDrainCommandDispatchSchemeCarService;
import com.gscitysfy.cus.drain.modules.command.service.IDrainCommandDispatchSchemeTeamService;
import com.gscitysfy.cus.drain.modules.command.service.ISchemeManageService;
import com.gscitysfy.cus.drain.modules.command.vo.SchemeManageQuery;
import com.gscitysfy.cus.drain.modules.inspection.entity.DrainInspectionMnProblem;
import com.gscitysfy.cus.drain.modules.inspection.vo.DrainInspectionMnProblemVo;
import com.gscitysfy.cus.drain.modules.pipe.entity.DrainPipeNetworkPlan;
import com.gscitysfy.cus.drain.modules.pipe.vo.DrainPipeNetworkPlanExcel;
import com.gscitysfy.cus.drain.utils.HttpResponseUtil;
import com.gscitysfy.cus.drain.utils.RedisUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 调度方案管理 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2022-10-20 18:58:46
 */
@AllArgsConstructor
@Service
public class SchemeManageServiceImpl extends ServiceImpl<SchemeManageMapper, SchemeManage> implements ISchemeManageService {

    private final SchemeManageConvert schemeManageConvert;
    @Autowired
    DrainCommandDispatchSchemeCarMapper drainCommandDispatchSchemeCarMapper;
    @Autowired
    DrainCommandDispatchSchemeTeamMapper drainCommandDispatchSchemeTeamMapper;
    @Autowired
    IDrainCommandDispatchSchemeCarService drainCommandDispatchSchemeCarService;
    @Autowired
    IDrainCommandDispatchSchemeTeamService drainCommandDispatchSchemeTeamService;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public IPage<SchemeManageDto> fetchPage(Page page, SchemeManageQuery query) {
        LambdaQueryWrapper<SchemeManage> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper = buildQueryWrapper(queryWrapper, query);
        Page<SchemeManage> schemeManagePage = this.page(page, queryWrapper);

        return schemeManagePage.convert(schemeManageConvert::toDto);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean saveOrUpdate(SchemeManageDto dto) {
        if (Objects.isNull(dto.getCmKid())) {
            //这里需要自动生成调度方案编码
            dto.setSchemeCode(currentDateCode());
            SchemeManage schemeManage = new SchemeManage();
            schemeManageConvert.toEntity(schemeManage, dto);
            return this.save(schemeManage);
        } else {
            SchemeManage schemeManage = baseMapper.selectById(dto.getCmKid());
            schemeManageConvert.toEntity(schemeManage, dto);
            return this.updateById(schemeManage);
        }
    }
    public String  currentDateCode(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentCode = sdf.format(date);

        int max=99;
        int min=10;
        Random random = new Random();
        String randomMath =  (random.nextInt(max - min) + min + 1)+"";
        String currentDateCode = "DDFA"+currentCode+randomMath;
        return currentDateCode;
    }




    @Override
    @Transactional
    public Boolean saveSchemeCar(SchemeManageDto dto) {
        //需要先将数据删除，然后再将新的数据插入
        //再新增
        Boolean result = true;
        List<DrainCommandDispatchSchemeCar> carList = dto.getCarList();
        for(DrainCommandDispatchSchemeCar drainCommandDispatchSchemeCar :carList){
                result = drainCommandDispatchSchemeCarService.save(drainCommandDispatchSchemeCar);
        }
        return result;
    }

    @Override
    public Boolean saveSchemeTeam(SchemeManageDto dto) {
        //再新增
        Boolean result = true;
        List<DrainCommandDispatchSchemeTeam> teamList = dto.getTeamList();
        for(DrainCommandDispatchSchemeTeam drainCommandDispatchSchemeTeam :teamList){
                 result = drainCommandDispatchSchemeTeamService.save(drainCommandDispatchSchemeTeam);
        }
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean delete(List<Long> idList) {
        List<SchemeManage> schemeManageList = new ArrayList<>();
        idList.forEach(id -> {
            SchemeManage schemeManage = baseMapper.selectById(id);
            schemeManage.setCmUsable(true);
            schemeManageList.add(schemeManage);
        });
        return this.updateBatchById(schemeManageList);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean enable(Long cmKid) {
        SchemeManage schemeManage = baseMapper.selectById(cmKid);
        schemeManage.setEnableFlag(!schemeManage.getEnableFlag());
        return this.updateById(schemeManage);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean audit(SchemeManageAuditDto dto) {
        List<SchemeManage> schemeManageList = new ArrayList<>();
        List<Long> idList = dto.getIdList();
        idList.forEach(id -> {
            SchemeManage schemeManage = baseMapper.selectById(id);
            schemeManage.setAuditStatus(dto.getAuditStatus());
            schemeManage.setAuditContent(dto.getAuditContent());
            schemeManageList.add(schemeManage);
        });
        return this.updateBatchById(schemeManageList);
    }

    @Override
    public void exportSchemeFile(HttpServletResponse response, SchemeManageDto dto) throws IOException{
        List<SchemeManage> schemeManageList = getSchemeFileListByCondition(dto);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<Object, Object> schemeCategory = redisUtil.hmget(RedisKeyConstant.DATA_DICT_KEY + DicConstant.COMMAND_SCHEME_CATEGORY);

        List<SchemeManageExcelDto> excelList = new ArrayList<>(16);
        schemeManageList.forEach(schemeManage -> {
            SchemeManageExcelDto excel = new SchemeManageExcelDto();
            BeanUtils.copyProperties(schemeManage, excel);
            excel.setCmAddTime(sdf1.format(schemeManage.getCmAddtime()));
            excel.setCmCreator(schemeManage.getCmCreator());
            excel.setEnableFlagDesc(schemeManage.getEnableFlag()?"是":"否");
            excel.setAuditStatusDesc(schemeManage.getAuditStatus()=="PASS"?"通过":"不通过");
            excel.setSchemeCategory(schemeCategory.get(schemeManage.getSchemeCategory()).toString());
            excelList.add(excel);
        });

        HttpResponseUtil.setResponseHeaders(response, "调度方案.xlsx");
        EasyExcel.write(response.getOutputStream(), SchemeManageExcelDto.class)
                .sheet("调度方案")
                .doWrite(() -> excelList);

    }
    /**
     * 导出问题列表
     * @param schemeManageDto
     * @return
     */
    public List<SchemeManage> getSchemeFileListByCondition(SchemeManageDto schemeManageDto) {
        LambdaQueryWrapper<SchemeManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SchemeManage::getCmUsable, false);
        if (StringUtils.isNotEmpty(schemeManageDto.getSchemeCategory())) {
            queryWrapper.eq(SchemeManage::getSchemeCategory, schemeManageDto.getSchemeCategory());
        }
        if (StringUtils.isNotEmpty(schemeManageDto.getSchemeName())) {
            queryWrapper.like(SchemeManage::getSchemeName, schemeManageDto.getSchemeName());
        }
        //更新时间倒排
        queryWrapper.orderByDesc(SchemeManage::getCmUptime);
        return this.list(queryWrapper);
    }
    /**
     * query组装
     *
     * @param queryWrapper
     * @param query
     * @return
     */
    public LambdaQueryWrapper<SchemeManage> buildQueryWrapper(LambdaQueryWrapper<SchemeManage> queryWrapper, SchemeManageQuery query) {
        if (StringUtils.isNotEmpty(query.getSchemeCategory())) {
            queryWrapper.eq(SchemeManage::getSchemeCategory, query.getSchemeCategory());
        }
        if (query.getPlanId()!=null) {
            queryWrapper.eq(SchemeManage::getPlanId, query.getPlanId());
        }
        if (query.getEnableFlag()!=null) {
            queryWrapper.eq(SchemeManage::getEnableFlag, query.getEnableFlag());
        }
        if (StringUtils.isNotEmpty(query.getAuditStatus())) {
            queryWrapper.eq(SchemeManage::getAuditStatus, query.getAuditStatus());
        }
        if (StringUtils.isNotEmpty(query.getSchemeCode())) {
            queryWrapper.like(SchemeManage::getSchemeCode, query.getSchemeCode());
        }

        if (StringUtils.isNotEmpty(query.getSchemeName())) {
            queryWrapper.like(SchemeManage::getSchemeName, query.getSchemeName());
        }
        if (StringUtils.isNotBlank(query.getBeginCreateTime()) && StringUtils.isNotBlank(query.getEndCreateTime())) {
            queryWrapper.ge(SchemeManage::getCmAddtime, LocalDateTime.parse(query.getBeginCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            queryWrapper.le(SchemeManage::getCmAddtime, LocalDateTime.parse(query.getEndCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        //删除标识
        queryWrapper.eq(SchemeManage::getCmUsable, query.getCmUsable());
        //更新时间倒排
        queryWrapper.orderByDesc(SchemeManage::getCmUptime);
        return queryWrapper;
    }
}
